<template>
  <div class="p-2">
    <!-- 排序功能提示 -->
    <!-- <div v-if="showSortTip" class="sort-tip" style="margin-bottom: 16px; padding: 12px; background: #f6ffed; border: 1px solid #b7eb8f; border-radius: 6px; position: relative;">
      <div style="display: flex; align-items: center; gap: 8px;">
        <span style="color: #52c41a; font-size: 16px;">💡</span>
        <span style="color: #52c41a; font-weight: 500;">排序功能说明：</span>
      </div>
      <div style="margin-top: 8px; color: #666; font-size: 13px;">
        • 点击"排序"列中的数字可直接编辑排序值
        • 支持批量选择题目后点击"批量排序"按钮自动排序
        • 排序值将用于移动端考试出题顺序
        • 按 Enter 键保存，按 Esc 键取消编辑
      </div>
      <button 
        @click="showSortTip = false" 
        style="position: absolute; top: 8px; right: 8px; background: none; border: none; color: #999; cursor: pointer; font-size: 16px;"
        title="关闭提示"
      >
        ×
      </button>
    </div> -->
    
    <!--查询区域-->
    <div class="jeecg-basic-table-form-container">
      <a-form ref="formRef" @keyup.enter.native="reload" :model="queryParam" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-row :gutter="24">
        </a-row>
      </a-form>
    </div>
    <!--引用表格-->
   <BasicTable @register="registerTable" :rowSelection="rowSelection">
     <!--插槽:table标题-->
      <template #tableTitle >
        <!-- v-auth="'examoptions:exam_questions:add'" -->
          <a-button type="primary"   @click="handleAdd" preIcon="ant-design:plus-outlined"> 新增</a-button>
         
          <a-button  type="primary" v-auth="'examoptions:exam_questions:exportXls'"  preIcon="ant-design:export-outlined" @click="onExportXls"> 导出</a-button>
          <j-upload-button  type="primary" v-auth="'examoptions:exam_questions:importExcel'"  preIcon="ant-design:import-outlined" @click="onImportXls">导入</j-upload-button>
          
          <!-- 批量排序按钮 -->
          <!-- <a-button 
            type="default" 
            @click="handleBatchSort" 
            preIcon="ant-design:ordered-list-outlined"
            :disabled="selectedRowKeys.length === 0"
          > 
            批量排序
          </a-button> -->
          
          <!-- 显示排序提示按钮 -->
          <a-button 
            v-if="!showSortTip"
            type="link" 
            @click="showSortTip = true" 
            preIcon="ant-design:question-circle-outlined"
            size="small"
          > 
            显示排序说明
          </a-button>
          
          <a-dropdown v-if="selectedRowKeys.length > 0">
              <template #overlay>
                <a-menu>
                  <a-menu-item key="1" @click="batchHandleDelete">
                    <Icon icon="ant-design:delete-outlined"></Icon>
                    删除
                  </a-menu-item>
                </a-menu>
              </template>
              <a-button v-auth="'examoptions:exam_questions:deleteBatch'">批量操作
                <Icon icon="mdi:chevron-down"></Icon>
              </a-button>
        </a-dropdown>
        <!-- 高级查询 -->
        <super-query :config="superQueryConfig" @search="handleSuperQuery" />
      </template>
       <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)"/>
      </template>
      <!--字段回显插槽-->
      <template v-slot:bodyCell="{ column, record, index, text }">
        <!-- 图片上传操作列 -->
        <template v-if="column.key === 'uploadAction'">
          <div class="upload-action-cell">
            <a-upload
              :show-upload-list="false"
              :before-upload="(file) => handleBeforeUpload(file, record)"
              :custom-request="(options) => handleUpload(options, record)"
              accept="image/*"
            >
              <a-button type="primary" size="small" :loading="uploadingMap[record.id]">
                <Icon icon="ant-design:upload-outlined" />
                上传图片
              </a-button>
            </a-upload>
          </div>
        </template>
        
        <!-- 题目图片显示列 -->
        <template v-if="column.key === 'examUrl'">
          <div class="exam-url-cell">
            <div v-if="record.examUrl" class="image-preview">
              <img :src="getImageUrl(record.examUrl)" alt="题目图片" @click="handlePreviewImage(record.examUrl)" />
            </div>
            <span v-else style="color: #999;">暂无图片</span>
          </div>
        </template>
      </template>
    </BasicTable>
    <!-- 表单区域 -->
    <ExamQuestionsModal @register="registerModal" @success="handleSuccess" :par_id = 'par_id'></ExamQuestionsModal>
    
    <!-- AnsweringInput 页面的表单区域 -->
    <AnsweringInputExamQuestionsModal @register="registerAnsweringInputModal" @success="handleSuccess" :par_id = 'par_id'></AnsweringInputExamQuestionsModal>
    
    <!-- 排序编辑模态框 -->
    <SortEditModal 
      v-model:open="sortEditModalOpen" 
      :record="editingRecord" 
      @success="handleSortEditSuccess"
    />
    
    <!-- 图片预览模态框 -->
    <a-modal
      v-model:open="previewVisible"
      title="图片预览"
      :footer="null"
      :width="800"
    >
      <img :src="previewImage" style="width: 100%;" alt="预览图片" />
    </a-modal>
  </div>
</template>

<script lang="ts" name="examoptions-examQuestions" setup>
  import {ref, reactive, computed, unref,onMounted, onUnmounted, h} from 'vue';
  import {BasicTable, useTable, TableAction} from '/@/components/Table';
  import { useListPage } from '/@/hooks/system/useListPage'
  import {useModal} from '/@/components/Modal';
  import ExamQuestionsModal from './components/ExamQuestionsModal.vue'
  // 导入 AnsweringInput 页面的组件
  import AnsweringInputExamQuestionsModal from '/@/views/answer/AnsweringInput/two_page/components/ExamQuestionsModal.vue'
  // 导入排序编辑模态框
  import SortEditModal from './components/SortEditModal.vue'
  import {columns, superQuerySchema} from './ExamQuestions.data';
  import {list, deleteOne, batchDelete, getImportUrl,getExportUrl, saveOrUpdate, uploadFile} from './ExamQuestions.api';
  import {downloadFile} from '/@/utils/common/renderUtils';
  import { useUserStore } from '/@/store/modules/user';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Icon } from '/@/components/Icon';
  import { useGlobSetting } from '/@/hooks/setting';
  const props = defineProps({
    par_id: Number,
  });
  console.log(props.par_id,"par_id")
  const formRef = ref();
  const queryParam = reactive<any>({});
  const checkedKeys = ref<Array<string | number>>([]);
  //注册model
  const [registerModal, {openModal}] = useModal();
  // 注册 AnsweringInput 页面的 modal
  const [registerAnsweringInputModal, {openModal: openAnsweringInputModal}] = useModal();
  const userStore = useUserStore();
  const { createMessage } = useMessage();
  const globSetting = useGlobSetting();
  
  // 排序编辑相关
  const isEditingSort = ref(false);
  const editingRecord = ref<Record<string, any> | undefined>(undefined);
  const editingValue = ref('');
  const showSortTip = ref(true);
  const sortEditModalOpen = ref(false);
  
  // 图片上传相关
  const uploadingMap = ref<Record<string, boolean>>({});
  const previewVisible = ref(false);
  const previewImage = ref('');
  
   //注册table数据
  const { prefixCls,tableContext,onExportXls,onImportXls } = useListPage({
      tableProps:{
           title: 'exam_questions（题目内容父表）',
           api: list,
           columns,
           canResize:false,
           useSearchForm: false,
           actionColumn: {
               width: 120,
               fixed:'right'
           },
           beforeFetch: async (params) => {
            console.log(params,"params")
            params.bankId = props.par_id
             return Object.assign(params, queryParam);
           },
        },
        exportConfig: {
            name:"exam_questions（题目内容父表）",
            url: getExportUrl,
            params: queryParam,
        },
        importConfig: {
            url: getImportUrl,
            success: handleSuccess
        },
    })

  const [registerTable, {reload},{ rowSelection, selectedRowKeys }] = tableContext
  // 高级查询配置
  const superQueryConfig = reactive(superQuerySchema);
// 页面加载时
onMounted(() => {
  // console.log(6660)
	// reload();
  
  // 监听排序编辑事件
  window.addEventListener('editSort', handleEditSort);
});

// 页面卸载时移除事件监听
onUnmounted(() => {
  window.removeEventListener('editSort', handleEditSort);
});

// 处理排序编辑
function handleEditSort(event) {
  try {
    const { record, currentValue } = event.detail;
    
    // 验证参数
    if (!record) {
      console.error('排序编辑参数无效');
      return;
    }
    
    // 设置编辑记录并打开模态框
    editingRecord.value = record;
    sortEditModalOpen.value = true;
    
  } catch (error) {
    console.error('排序编辑处理失败:', error);
  }
}

// 处理排序编辑成功
async function handleSortEditSuccess(data) {
  try {
    // 构建完整的编辑数据，包含原有记录的所有字段
    const editData = {
      ...editingRecord.value, // 包含原有记录的所有字段
      sort: data.sort // 更新排序字段
    };
    
    // 调用编辑接口
    await saveOrUpdate(editData, true);
    
    // 重新加载表格数据以显示更新后的排序
    reload();
    
  } catch (error) {
    console.error('排序更新失败:', error);
    createMessage.error('排序更新失败，请重试');
  }
}
  /**
   * 高级查询事件
   */
  function handleSuperQuery(params) {
    Object.keys(params).map((k) => {
      queryParam[k] = params[k];
    });
    reload();
  }

   /**
    * 新增事件
    */
  function handleAdd() {
    console.log(props.par_id,"record")
     openModal(true, {
       isUpdate: false,
       showFooter: true,
     });
  }
   /**
    * 编辑事件
    */
  
   /**
    * 详情
   */
  function handleDetail(record: Recordable) {
     // 使用 AnsweringInput 页面的详情功能
     openAnsweringInputModal(true, {
       record,
       isUpdate: true,
       showFooter: false,
     });
   }
   /**
    * 删除事件
    */
  async function handleDelete(record) {
     await deleteOne({id: record.id}, handleSuccess);
   }
   /**
    * 批量删除事件
    */
  async function batchHandleDelete() {
     await batchDelete({ids: selectedRowKeys.value},handleSuccess);
   }
   /**
    * 成功回调
    */
  function handleSuccess() {
      (selectedRowKeys.value = []) && reload();
   }
   
   /**
    * 批量排序处理
    */
  function handleBatchSort() {
    if (selectedRowKeys.value.length === 0) {
      createMessage.warning('请先选择要排序的题目');
      return;
    }
    
    // 获取选中的记录
    const selectedRecords = selectedRowKeys.value.map(key => {
      // 这里需要根据实际情况获取记录数据
      return { id: key };
    });
    
    // 显示排序对话框
    createMessage.info(`已选择 ${selectedRecords.length} 个题目进行批量排序`);
    
    // 这里可以实现一个排序对话框，让用户输入排序规则
    // 暂时使用简单的自动排序
    autoSortSelectedQuestions(selectedRecords);
  }
  
  /**
    * 自动排序选中的题目
    */
  async function autoSortSelectedQuestions(records) {
    try {
      const promises = records.map((record, index) => {
        return saveOrUpdate({
          id: record.id,
          sort: index + 1
        }, true);
      });
      
      await Promise.all(promises);
      createMessage.success('批量排序完成');
      reload();
    } catch (error) {
      console.error('批量排序失败:', error);
      createMessage.error('批量排序失败');
    }
  }
   /**
      * 操作栏
      */
  function getTableAction(_record){
       return [];
   }
     /**
        * 下拉操作栏
        */
  function getDropDownAction(record){
       return [
         {
           label: '详情',
           onClick: handleDetail.bind(null, record),
         }, {
           label: '删除',
           popConfirm: {
             title: '是否确认删除',
             confirm: handleDelete.bind(null, record),
             placement: 'topLeft'
           },
          //  auth: 'examoptions:exam_questions:delete'
         }
       ]
   }

  

  /* ----------------------以下为原生查询需要添加的-------------------------- */
  const toggleSearchStatus = ref<boolean>(false);
  const labelCol = reactive({
    xs:24,
    sm:4,
    xl:6,
    xxl:4
  });
  const wrapperCol = reactive({
    xs: 24,
    sm: 20,
  });
  /**
   * 重置
   */
  function searchReset() {
    formRef.value.resetFields();
    selectedRowKeys.value = [];
    //刷新数据
    reload();
  }

  /**
   * 获取图片完整URL
   */
  function getImageUrl(url: string) {
    if (!url) return '';
    // 如果是完整URL，直接返回
    if (url.startsWith('http://') || url.startsWith('https://')) {
      return url;
    }
    // 拼接固定的图片访问前缀
    const imagePrefix = 'http://124.222.44.60:9090/jeecg-boot/sys/common/static/';
    return `${imagePrefix}${url}`;
  }

  /**
   * 上传前校验
   */
  function handleBeforeUpload(file: File, record: any) {
    const isImage = file.type.startsWith('image/');
    if (!isImage) {
      createMessage.error('只能上传图片文件！');
      return false;
    }
    const isLt5M = file.size / 1024 / 1024 < 5;
    if (!isLt5M) {
      createMessage.error('图片大小不能超过 5MB！');
      return false;
    }
    return true;
  }

  /**
   * 处理文件上传
   */
  async function handleUpload(options: any, record: any) {
    const { file } = options;
    
    try {
      // 设置上传中状态
      uploadingMap.value[record.id] = true;
      
      // 第一步：调用上传接口
      console.log('开始上传文件...');
      const result = await uploadFile({
        file: file,
        name: 'file',
      });
      
      console.log('文件上传接口返回结果:', result);
      
      // 获取返回的文件名
      let fileName = '';
      if (result && result.message) {
        fileName = result.message;
        console.log('✅ 成功获取文件名:', fileName);
      } else if (result && result.url) {
        fileName = result.url;
        console.log('✅ 从url获取文件名:', fileName);
      }
      
      if (!fileName) {
        console.error('❌ 未能从返回结果中获取文件名, result:', result);
        throw new Error('上传失败，未返回文件名');
      }
      
      // 第二步：调用编辑接口，只传递必要的字段 + examUrl
      const editParams: Record<string, any> = {
        id: record?.id,
        bankId: record?.bankId,
        content: record?.content,
        sort: record?.sort,
        isMultipleChoice: record?.isMultipleChoice,
        valueOfScore: record?.valueOfScore,
        correctAnswer: record?.correctAnswer,
        isPublic: record?.isPublic,
        other: record?.other,
        other2: record?.other2,
        examUrl: fileName  // 添加图片路径参数
      };
      
      console.log('准备调用编辑接口，参数:', editParams);
      const editResult = await saveOrUpdate(editParams, true);
      console.log('✅ 编辑接口调用成功，返回:', editResult);
      
      createMessage.success('图片上传成功！');
      
      // 刷新表格数据
      reload();
      
    } catch (error: any) {
      console.error('❌ 操作失败，错误详情:', error);
      console.error('错误堆栈:', error?.stack);
      createMessage.error('图片上传失败，请重试！');
    } finally {
      // 清除上传中状态
      uploadingMap.value[record.id] = false;
    }
  }

  /**
   * 预览图片
   */
  function handlePreviewImage(url: string) {
    previewImage.value = getImageUrl(url);
    previewVisible.value = true;
  }

</script>
<style lang="less" scoped>
  .jeecg-basic-table-form-container {
    padding: 0;
    .table-page-search-submitButtons {
      display: block;
      margin-bottom: 24px;
      white-space: nowrap;
    }
    .query-group-cust{
      min-width: 100px !important;
    }
    .query-group-split-cust{
      width: 30px;
      display: inline-block;
      text-align: center
    }
    .ant-form-item:not(.ant-form-item-with-help){
      margin-bottom: 16px;
      height: 32px;
    }
    :deep(.ant-picker),:deep(.ant-input-number){
      width: 100%;
    }
  }
  
  // 排序字段样式
  :deep(.sort-cell) {
    transition: all 0.3s ease;
    user-select: none;
    
    &:hover {
      background-color: #e6f7ff !important;
      border-color: #1890ff !important;
      transform: scale(1.05);
      box-shadow: 0 2px 8px rgba(24, 144, 255, 0.15);
    }
    
    &:active {
      transform: scale(0.95);
    }
    
    // 拖拽图标样式
    .drag-icon {
      opacity: 0.6;
      transition: opacity 0.3s ease;
    }
    
    &:hover .drag-icon {
      opacity: 1;
    }
  }
  
  // 排序输入框样式
  :deep(.sort-input) {
    width: 60px;
    height: 32px;
    border: 1px solid #1890ff;
    border-radius: 4px;
    padding: 4px 8px;
    text-align: center;
    font-size: 14px;
    outline: none;
    
    &:focus {
      border-color: #40a9ff;
      box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
    }
  }
  
  // 图片上传操作列样式
  .upload-action-cell {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  
  // 题目图片显示列样式
  .exam-url-cell {
    display: flex;
    justify-content: center;
    align-items: center;
    
    .image-preview {
      display: flex;
      justify-content: center;
      align-items: center;
      
      img {
        width: 80px;
        height: 80px;
        object-fit: cover;
        border-radius: 6px;
        border: 1px solid #d9d9d9;
        cursor: pointer;
        transition: all 0.3s ease;
        
        &:hover {
          border-color: #1890ff;
          transform: scale(1.15);
          box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
        }
      }
    }
  }
</style>